package com.hrhx.springboot.crawler.fund;

import com.alibaba.fastjson.JSON;
import com.hrhx.springboot.domain.FundComany;
import com.hrhx.springboot.mysql.jpa.FundComanyRepository;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author duhongming
 * @version 1.0
 * @description TODO
 * @date 2020/3/26 17:29
 */
@RestController
@RequestMapping
public class FundCompanyCrawller {

    @Autowired
    private FundComanyRepository fundComanyRepository;
    /**
     * 基金公司排名列表
     */
    public static final String FUND_COMPANY_LIST_API = "http://fund.eastmoney.com/Data/FundRankScale.aspx";
    /**
     * 基金经理管理基金一览
     */
    public static final String FUND_COMPANY_INFO_API = "http://fund.eastmoney.com/Company/f10/jjjl_${fund_company_id}.html";

    @RequestMapping("/fund/company/save")
    public void save() throws IOException {
        Document fundCompanyDoc = Jsoup.connect(FUND_COMPANY_LIST_API).get();
        String fundCompanyJson = fundCompanyDoc.select("body").text().replace("var json=", "");
        FundCompanyData fundCompanyData = JSON.parseObject(fundCompanyJson, FundCompanyData.class);
        List<FundComany> fundComanies = new ArrayList<>();
        List<List<String>> datas = fundCompanyData.getDatas();
        for (List<String> data : datas) {
            FundComany fundComany = new FundComany();
            if (StringUtils.isNotBlank(data.get(0))) {
                fundComany.setFundCompanyId(Integer.parseInt(data.get(0)));
            }
            fundComany.setFundCompanyFullName(data.get(1));
            fundComany.setEstablishDate(data.get(2));
            if (StringUtils.isNotBlank(data.get(3))) {
                fundComany.setFundsCount(Integer.parseInt(data.get(3)));
            }
            fundComany.setFundCompanyManager(data.get(4));
            fundComany.setFundCompanyPyName(data.get(5));
            fundComany.setField1(data.get(6));
            if (StringUtils.isNotBlank(data.get(7))) {
                fundComany.setFundsAmount(Double.parseDouble(data.get(7)));
            }
            fundComany.setRankingStar(data.get(8));
            fundComany.setFundCompanySimpleName(data.get(9));
            fundComany.setField2(data.get(10));
            fundComany.setCmpTime(data.get(11));
            fundComanies.add(fundComany);
        }
        fundComanyRepository.save(fundComanies);
    }
}

@Getter
@Setter
class FundCompanyData {
    private List<List<String>> datas;
}